Entity Framework (EF) Core 是一種資料存取技術,EF Core 是物件關聯對應 (ORM) 框架
,以下為它的特性
輕量型
可擴充
開源
跨平台
dotnet ef
必須安裝為全域。
dotnet tool install --global dotnet-ef
dotnet new console -o EFSample
cd EFSample
資料庫提供者,用來與資料庫溝通(其他資料庫提供者)
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
安裝最新的 Microsoft.EntityFrameworkCore.Design 套件
dotnet add package Microsoft.EntityFrameworkCore.Design
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public string DbPath { get; }
public BloggingContext()
{
var folder = Environment.SpecialFolder.LocalApplicationData;
var path = Environment.GetFolderPath(folder);
DbPath = System.IO.Path.Join(path, "blogging.db");
}
// The following configures EF to create a Sqlite database file in the
// special "local" folder for your platform.
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={DbPath}");
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; } = new();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
dotnet ef migrations add InitialCreate
dotnet ef database update
Program.cs
using System;
using System.Linq;
using var db = new BloggingContext();
// 這個資料庫需要在建置前被建立
Console.WriteLine($"Database path: {db.DbPath}.");
// 建立
Console.WriteLine("建立一個新的 blog");
db.Add(new Blog { Url = "https://ithelp.ithome.com.tw/notifications" });
db.SaveChanges();
// 讀取
Console.WriteLine("查詢一個 blog");
var blog = db.Blogs
.OrderBy(b => b.BlogId)
.First();
// 更新
Console.WriteLine("更新 blog and 加一個 post");
blog.Url = "https://devblogs.microsoft.com/dotnet";
blog.Posts.Add(
new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
db.SaveChanges();
// 刪除
Console.WriteLine("刪除 blog");
db.Remove(blog);
db.SaveChanges();
dotnet run